package com.example.bitmapandcachedemo.imageloader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.example.bitmapandcachedemo.R;

import java.util.List;

/**
 * Created by tangjiangxu on 11/8/17.
 */

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private List<String> mUrlList;
    private LayoutInflater mInflater;
    public static boolean mIsGridViewIdle = true;

    public ImageAdapter(Context context, List<String> mUrlList) {
        this.mContext = context;
        mInflater = LayoutInflater.from(context);
        this.mUrlList = mUrlList;
    }

    @Override
    public int getCount() {
        if (mUrlList != null) {
            return mUrlList.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (mUrlList != null) {
            return mUrlList.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.photo_item, parent, false);
            holder = new ViewHolder();
            holder.imageView = convertView.findViewById(R.id.image);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        ImageView imageView = holder.imageView;
        final String tag = (String) imageView.getTag();
        final String uri = (String) getItem(position);
        Bitmap mDefaultBitmapDrawable = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
        if (!uri.equals(tag)) {
            imageView.setImageBitmap(mDefaultBitmapDrawable);
        }
        if (mIsGridViewIdle) {
            imageView.setTag(uri);
            ImageLoader.getInstance(mContext).bindBitmap(uri, imageView, 0, 0);
        }
        return convertView;
    }


    class ViewHolder {
        ImageView imageView;
    }
}
